<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input
        v-model="listQuery.account"
        placeholder="请输入搜索账号"
        style="width: 300px"
        class="filter-item"
        maxlength="11"
        @keyup.enter.native="handleFilter"
      />
      <el-select v-model="listQuery.sort" style="width: 100px; margin-left: 15px" class="filter-item" @change="handleFilter">
        <el-option v-for="item in sortOptions" :key="item.key" :label="item.label" :value="item.key" />
      </el-select>
      <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter" style="margin-left: 15px">
        {{ '搜索' }}
      </el-button>
      <el-button
        v-if="getValid('创建权限')"
        class="filter-item"
        style="margin-left: 15px"
        type="primary"
        icon="el-icon-circle-plus-outline"
        @click="handleCreate"
      >
        {{ '添加' }}
      </el-button>
      <el-button class="filter-item" style="margin-left: 15px" type="primary" icon="el-icon-refresh" @click="handleFilter">
        {{ '刷新' }}
      </el-button>
    </div>
    <el-table :key="tableKey" v-loading="listLoading" :data="list" border fit highlight-current-row style="width: 100%">
      <el-table-column label="id" prop="id" sortable="custom" align="center" width="80" :class-name="getSortClass('id')">
        <template slot-scope="{ row }">
          <span>{{ row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column label="客服账号" width="120px" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.account }}</span>
        </template>
      </el-table-column>
      <el-table-column label="客服姓名" width="120px" align="center" class-name="fixed-width">
        <template slot-scope="{ row }">
          <span>{{ row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="手机号码" width="120px" align="center" class-name="fixed-width">
        <template slot-scope="{ row }">
          <span>{{ row.phone }}</span>
        </template>
      </el-table-column>
      <el-table-column label="所属上级" width="110px" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.parent }}</span>
        </template>
      </el-table-column>
      <el-table-column label="注册时间" align="center" width="200">
        <template slot-scope="{ row }">
          <span>{{ row.regTime }}</span>
        </template>
      </el-table-column>
      <el-table-column label="客服用户" align="center" width="80">
        <template slot-scope="{ row }">
          <span>{{ row.directCount }}</span>
        </template>
      </el-table-column>
      <el-table-column label="最后登录" align="center" width="200">
        <template slot-scope="{ row }">
          <span>{{ row.lastTime }}</span>
        </template>
      </el-table-column>
      <el-table-column label="登录次数" align="center" width="80">
        <template slot-scope="{ row }">
          <span>{{ row.loginCount }}</span>
        </template>
      </el-table-column>
      <el-table-column label="当前状态" align="center" width="80">
        <template slot-scope="{ row }">
          <span>{{ row.status ? '正常' : '锁定' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="230" class-name="fixed-width">
        <template slot-scope="{ row, $index }">
          <el-button v-if="getValid('编辑权限')" type="primary" size="mini" @click="handleUpdate(row)">
            {{ '编辑' }}
          </el-button>
          <el-button
            v-if="getValid('封禁权限')"
            size="mini"
            :type="row.status ? '' : 'warning'"
            @click="handleModifyStatus(row)"
          >
            {{ row.status ? '锁定' : '解锁' }}
          </el-button>
          <el-button v-if="getValid('删除权限')" size="mini" type="danger" @click="handleDelete(row, $index)">
            {{ '删除' }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.limit"
      @pagination="getList"
    />
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" :close-on-click-modal="false">
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="tempData"
        label-position="left"
        label-width="100px"
        style="width: 400px; margin-left: 50px"
      >
        <el-form-item label="客服账号" prop="account">
          <el-input v-model="tempData.account" maxlength="11" placeholder="请输入5-11位账号" />
        </el-form-item>
        <el-form-item label="客服密码" prop="password">
          <el-input v-model="tempData.password" maxlength="11" type="password" placeholder="请输入5-11位密码" />
        </el-form-item>
        <el-form-item label="用户姓名" prop="name">
          <el-input v-model="tempData.name" maxlength="6" minlength="2" placeholder="请输入2-6位用户姓名" />
        </el-form-item>
        <el-form-item label="手机号码" prop="phone">
          <el-input v-model="tempData.phone" maxlength="11" placeholder="请输入11位手机号码" />
        </el-form-item>
        <el-form-item label="上级账户" prop="parent">
          <el-input v-model="tempData.parent" maxlength="11" disabled />
        </el-form-item>
        <el-form-item label="是否启用">
          <el-checkbox v-model="tempData.status" class="filter-item" style="margin-left: 15px">
            {{ '立即启用' }}
          </el-checkbox>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          {{ '取消' }}
        </el-button>
        <el-button type="primary" @click="dialogStatus === 'create' ? createData() : updateData()">
          {{ '确认' }}
        </el-button>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="dialogPageviewsVisible" title="Reading statistics">
      <el-table :data="pageviewsData" border fit highlight-current-row style="width: 100%">
        <el-table-column prop="key" label="Channel" />
        <el-table-column prop="pageviews" label="Pageviews" />
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogPageviewsVisible = false">{{ '确认' }}</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script lang="ts">
import { Component, Vue } from 'vue-property-decorator';
import { Form } from 'element-ui';
import Pagination from '@/components/Pagination/index.vue';
import { createAgent, deleteAgent, getAgentList, updateAgent, updateAgentStatus } from '@/api/admin';
import { ManagerModule } from '@/store/modules/manager';
@Component({
  name: 'Customer',
  components: {
    Pagination
  }
})
export default class extends Vue {
  [x: string]: any;
  tableKey = 0;
  list: Agent[] = [];
  total = 0;
  isOpen = true;
  listLoading = true;
  listQuery = {
    page: 1,
    limit: 20,
    account: '',
    sort: '+id'
  };
  sortOptions = [
    { label: 'id 升序', key: '+id' },
    { label: 'id 降序', key: '-id' }
  ];
  dialogFormVisible = false;
  dialogStatus: any = '';
  textMap: any = {
    update: '编辑客服',
    create: '创建客服'
  };
  dialogPageviewsVisible = false;
  pageviewsData = [];
  rules = {
    name: [
      { required: false, message: '该字段不能为空', trigger: 'blur' },
      {
        pattern: /^$|^.{2,6}$/,
        message: '名字长度必须为 2到6 个字符',
        trigger: 'blur'
      }
    ],
    phone: [
      { required: false, message: '该字段不能为空', trigger: 'blur' },
      {
        pattern: /^1[3-9]\d{9}$/,
        message: '请输入有效的手机号',
        trigger: 'blur'
      }
    ],
    account: [
      { required: true, message: '该字段不能为空', trigger: 'blur' },
      {
        pattern: /^$|^.{5,11}$/,
        message: '账号长度必须为 5到11 个字符',
        trigger: 'blur'
      }
    ],
    parent: [
      { required: true, message: '该字段不能为空', trigger: 'blur' },
      {
        pattern: /^$|^.{5,11}$/,
        message: '上级账号长度必须为 5到11 个字符',
        trigger: 'blur'
      }
    ],
    password: [
      { required: true, message: '该字段不能为空', trigger: 'blur' },
      {
        pattern: /^$|^.{5,11}$/,
        message: '密码长度必须为 5到11 个字符',
        trigger: 'blur'
      }
    ]
  };
  downloadLoading = false;
  tempData: TReq.AgentCreat = {
    account: '',
    phone: '',
    name: '',
    parent: ManagerModule.managerData.account,
    password: '',
    status: true
  };
  //获取权限
  getValid(type: TRole.Author): boolean {
    const temp = ManagerModule?.roles?.客服管理;
    if (temp && temp[type]) {
      return true;
    } else {
      return false;
    }
  }
  //初始化获取用户
  created() {
    this.getList();
  }
  //获取用户列表
  async getList() {
    this.listLoading = true;
    setTimeout(() => {
      this.listLoading = false;
    }, 500);
    const ret = await getAgentList(this.listQuery);
    if (ret?.status) {
      this.list = ret.data;
      this.total = ret.data.length;
      return;
    }
    this.$msgErr(ret?.msg || '获取失败');
  }
  //搜索过滤
  handleFilter() {
    this.listQuery.page = 1;
    this.getList();
  }
  //排序改变
  sortChange(data: any) {
    const { prop, order } = data;
    if (prop === 'id') {
      if (order === 'ascending') {
        this.listQuery.sort = '+id';
      } else {
        this.listQuery.sort = '-id';
      }
      this.handleFilter();
    }
  }
  //更新状态
  async handleModifyStatus(row: any) {
    const ret = await updateAgentStatus(row.status);
    if (ret?.status) {
      row.status = ret.data;
      this.$msgSuc(ret?.msg || '更新成功');
      return;
    }
    this.$msgErr(ret?.msg || '更新失败');
  }
  //获取排序类名
  getSortClass(key: string) {
    const sort = this.listQuery.sort;
    return sort === `+${key}` ? 'ascending' : 'descending';
  }
  //重置数据
  resetTempData() {
    this.tempData = {
      account: '',
      phone: '',
      name: '',
      parent: ManagerModule.managerData.account,
      password: '',
      status: true
    };
  }
  //打开创建面板
  handleCreate() {
    this.resetTempData();
    this.rules.password[0].required = true;
    this.dialogStatus = 'create';
    this.dialogFormVisible = true;
    this.$nextTick(() => {
      (this.$refs.dataForm as Form).clearValidate();
    });
  }
  //更新编辑框
  handleUpdate(row: any) {
    this.rules.password[0].required = false;
    const temp: TReq.AgentCreat = {
      account: row.account,
      password: '',
      phone: row.phone || '',
      name: row.name || '',
      status: row.status,
      parent: row.parent
    };
    this.tempData = temp;
    this.dialogStatus = 'update';
    this.dialogFormVisible = true;
    this.$nextTick(() => {
      (this.$refs.dataForm as Form).clearValidate();
    });
  }
  //删除用户
  async handleDelete(row: any, index: number) {
    const ret = await deleteAgent(row.account);
    if (ret?.status) {
      this.list.splice(index, 1);
      this.$msgSuc(ret?.msg || '删除成功');
      return;
    }
    this.$msgErr(ret?.msg || '删除失败');
  }
  //创建用户确定
  createData() {
    (this.$refs.dataForm as Form).validate(async (valid) => {
      if (valid) {
        this.dialogFormVisible = false;
        const ret = await createAgent(this.tempData);
        if (ret.status) {
          this.list.unshift(ret.data);
          this.$msgSuc(ret?.msg || '创建成功');
          return;
        }
        this.$msgErr(ret?.msg || '创建失败');
      }
    });
  }
  //更新用户确定
  updateData() {
    (this.$refs.dataForm as Form).validate(async (valid) => {
      if (valid) {
        this.dialogFormVisible = false;
        const tempData = Object.assign({}, this.tempData);
        const ret = await updateAgent(tempData);
        if (ret?.status) {
          const index = this.list.findIndex((v) => v.account === ret.data.account);
          this.list.splice(index, 1, ret.data);
          this.$msgSuc(ret?.msg || '创建成功');
          return;
        }
        this.$msgErr(ret?.msg || '创建失败');
      }
    });
  }
  //分页
  async handleGetPageviews(pageviews: string) {
    // const { data } = await getPageviews({ pageviews });
    // this.pageviewsData = data.pageviews;
    // this.dialogPageviewsVisible = true;
  }
}
</script>
